<template>
    <view class="page">
        <view class="header">
            <uni-icons type="left" size="25" class="back-icon" @click="goBack"></uni-icons>
            <view class="top-toggle-btns">
                <view class="top-toggle-btn-left">身高</view>
                <view class="top-toggle-btn-right" @click="enterweight">体重</view>
            </view>
        </view>
        
        <view class="toggle-btns">
            <view class="toggle-btn toggle-btn-left" :class="{'active': toggle === 0}" @click="toggle = 0">曲线</view>
            <view class="toggle-btn toggle-btn-right" :class="{'active': toggle === 1}" @click="toggle = 1">记录</view>
        </view>
        
        <view class="charts-box" v-if="toggle === 0">
            <qiun-data-charts type="area" :opts="opts" :chartData="chartData" />
        </view>
        
        <view class="record-box" v-if="toggle === 1">
                <view class="record-item no-arrow">
                    <view class="record-age">年龄</view>
                    <view class="record-height">身高</view>
                </view>
                <view class="record-item" v-for="(item, index) in growthRecords" :key="index">
                    <view class="record-age">{{ calculateMonthAge(item.birthDay, item.recordDate) }}</view>
                    <view class="record-height"><text>{{ item.height }}</text>cm</view>
                </view>
            </view>
        
        <button class="add-btn" @click="goToAdd">添加记录</button>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// 响应式数据
const toggle = ref(0);
const chartData = ref({});
const growthRecords = ref([]);

// 图表配置
const opts = {
    color: ["#666ee8"],
    padding: [50, 15, 15, 15],
    enableScroll: false,
    legend: {},
    xAxis: {
        disableGrid: true
    },
    yAxis: {
        gridType: "dash",
        dashLength: 2,
        data: [{
            title: "单位：cm",
            titleOffsetX: 8,
            titleOffsetY: -20
        }],
        showTitle: true
    },
    extra: {
        area: {
            type: "straight",
            opacity: 0.2,
            addLine: true,
            width: 2,
            gradient: true,
            activeType: "hollow"
        }
    }
};

// 计算月龄
const calculateMonthAge = (startDate, endDate) => {
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    let months = (end.getFullYear() - start.getFullYear()) * 12;
    months += end.getMonth() - start.getMonth();
    
    // 调整天数差异
    if (end.getDate() < start.getDate()) {
        months--;
    }
    
    if (months === 0) {
        return '出生';
    } else if (months < 24) {  // 小于2岁（24个月）时显示月份
        return `${months}个月`;
    } else {  // 大于等于2岁时只显示岁
        const years = Math.floor(months / 12);
        return `${years}岁`;
    }
};

// 获取图表数据
const getChartData = async () => {
    try {
        const res = await uni.request({
            url: 'http://localhost:9100/api/growthrecord/selectRecordList',
            method: 'GET',
            data: {
                babyId: uni.getStorageSync('babyId')
            },
            header: {
                'bece_token': uni.getStorageSync('bece_token')
            }
        });

        if (res.data.code === 200) {
            const records = res.data.data;
            // 按日期排序
            records.sort((a, b) => new Date(a.recordDate) - new Date(b.recordDate));
            growthRecords.value = records;

            if (records.length > 0) {
                const birthDay = records[0].birthDay;
                
                // 转换数据为图表格式
                const chartDataFormat = {
                    categories: records.map(item => calculateMonthAge(birthDay, item.recordDate)),
                    series: [{
                        name: "身高",
                        data: records.map(item => item.height)
                    }]
                };
                
                chartData.value = chartDataFormat;
            }
        } else {
            uni.showToast({
                title: res.data.msg || '获取数据失败',
                icon: 'error'
            });
        }
    } catch (error) {
        console.error('获取数据失败:', error);
        uni.showToast({
            title: '网络错误',
            icon: 'error'
        });
    }
};

// 格式化日期
const formatDate = (dateString) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 返回上一页
const goBack = () => {
    uni.navigateBack();
};

// 跳转到添加记录页面
const goToAdd = () => {
    uni.navigateTo({
        url: '/pages/baby/add_record/add_record'
    });
};

const enterweight = () => {
    uni.navigateTo({
        url: '/pages/baby/growth_record_weight/growth_record_weight'
    });
};

// 页面加载完成后获取数据
onMounted(() => {
    getChartData();
});
</script>

<style scoped>
.page{
	position: relative;
}

.header{
	border-bottom: solid #f2f2f2;
	margin: 20rpx auto;
}

.back-icon{
	position: fixed;
	padding-top: 8rpx;
	padding-left: 12rpx;
}

.top-toggle-btns {
	display: flex;
	justify-content: center;
	margin: auto;
}

.top-toggle-btn-right {
	width: 220rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	color: #000;
	cursor: pointer;
}
.top-toggle-btn-left {
	width: 220rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	color: #666ee8;
	border-bottom: solid #666ee8;
	cursor: pointer;
}

.toggle-btns {
	display: flex;
	justify-content: center;
	margin: 70rpx auto;
}

.toggle-btn {
	width: 220rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	color: #999;
	background-color: #fff;
	border: 1px solid #f2f2f2;
	cursor: pointer;
}

.toggle-btn.active {
	color: #fff;
	background-color: #666ee8;
	border-color: #666ee8;
}

.toggle-btn-left {
	border-right: none;
	border-top-left-radius: 60rpx;
	border-bottom-left-radius: 60rpx;
}

.toggle-btn-right {
	border-left: none;
	border-top-right-radius: 60rpx;
	border-bottom-right-radius: 60rpx;
}

.charts-box {
	height: 300px;
	margin: 60rpx 40rpx 60rpx;
	background-color: #fff;
	border-radius: 8rpx;
	box-shadow: 0px 2px 10px rgba(204, 204, 204, 0.4);
}

.record-box {
	margin: 60rpx 40rpx 60rpx;
	background-color: #fff;
	border-radius: 8rpx;
	box-shadow: 0px 2px 10px rgba(204, 204, 204, 0.4);
}

.record-item {
	display: flex;
	height: 100rpx;
	line-height: 100rpx;
	padding: 0 50rpx;
	font-size: 28rpx;
	color: #333;
	border-bottom: 1px solid #f2f2f2;
	cursor: pointer;
}

.record-item::after {
	content: ">";
	font-size: 36rpx;
	color: #ccc;
}

.record-item.no-arrow::after {
	visibility: hidden;
}

.record-age,
.record-height {
	flex: 1;
}

.record-height text {
	font-size: 36rpx;
	font-weight: bold;
	color: #666ee8;
}

.add-btn {
	height: 88rpx;
	line-height: 88rpx;
	margin: auto 40rpx;
	font-size: 32rpx;
	color: #fff;
	background-color: #666ee8;
	border: none;
	border-radius: 88rpx;
}
</style>
